import 'dart:async';

typedef OnRemainDuration = void Function(Duration duration);
typedef OnFinish = void Function();

class TimerUtil {
  Duration _duration = Duration.zero;
  Timer? _timer;
  OnRemainDuration? _onRemainDuration;
  OnFinish? _onFinish;
  TimerUtil();
  void startCountdown(
      Duration duration, OnRemainDuration onRemainDuration, OnFinish onFinish) {
    _duration = duration;
    _onRemainDuration = onRemainDuration;
    _onFinish = onFinish;

    _timer = Timer.periodic(const Duration(seconds: 1), _tick);
  }

  void _tick(Timer timer) {
    _duration = _duration - const Duration(seconds: 1);
    if (_onRemainDuration != null) {
      _onRemainDuration!(_duration);
    }
    if (_duration <= Duration.zero) {
      _timer?.cancel();
      if (_onFinish != null) {
        _onFinish!();
      }
    }
  }

  void pause() {
    _timer?.cancel();
  }

  void resume() {
    if (_duration > Duration.zero) {
      _timer = Timer.periodic(const Duration(seconds: 1), _tick);
    }
  }

  void interrupt() {
    _timer?.cancel();
    _duration = Duration.zero;
    if (_onRemainDuration != null) {
      _onRemainDuration!(_duration);
    }
  }
}
